package com.aletto.general_store.presenters;

import android.view.View;
import android.view.ViewGroup;

import com.aletto.general_store.data.entities.WalletAccount;
import com.aletto.general_store.data.model.Goods;
import com.aletto.general_store.data.model.Response;
import com.aletto.general_store.ui.adapters.WalletAccountAdapter;
import com.aletto.general_store.utils.LocalConfigStore;
import com.aletto.general_store.utils.WalletAccountLocalStore;
import com.aletto.general_store.utils.event.LoginEvent;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.network.presenters.NetSingleTask;
import com.sisyphus.spinach.network.views.QuickList;
import com.sisyphus.spinach.ui.configs.impl.DefaultTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.rxjava3.core.Observable;

public class WalletAccountTemplate extends DefaultTemplate<List<WalletAccount>> {

    private final RecyclerView mRecyclerView;

    public WalletAccountTemplate(RecyclerView parent) {
        super(parent);
        mRecyclerView = parent;
    }

    @Override
    public INetTask.View<List<WalletAccount>> view() {
        WalletAccountAdapter adapter = new WalletAccountAdapter();

        adapter.setOnItemClickListener((a, view, position) -> {
            WalletAccount wallet = LocalConfigStore.getInstance().getWallet();

            // 点击为当前钱包，直接返回
            if (wallet.getAddress().equals(adapter.getItem(position).getAddress())){
                return;
            }

            List<WalletAccount> data = adapter.getData();
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getAddress().equals(wallet.getAddress())) {
                    a.notifyItemChanged(i);
                    break;
                }
            }

            // 更新
            LocalConfigStore.getInstance().setWallet(adapter.getItem(position));
            a.notifyItemChanged(position);
            EventBus.getDefault().post(new LoginEvent());
        });

        mRecyclerView.setAdapter(adapter);
        return new QuickList<>(adapter);
    }

    @Override
    public INetTask.Presenter<List<WalletAccount>, INetTask.View<List<WalletAccount>>> presenter() {
        return new NetSingleTask<>(Observable.create(emitter -> {

            emitter.onNext(new Response<>(
                    WalletAccountLocalStore.getInstance().accounts()
            ));

            emitter.onComplete();
        }));
    }

}
